package webservices;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import classes.Market;
import classes.Narudzbenica;
import dao.DAOFactory;

@Path("/narudzbenice")
public class NarudzbenicaResource {
	 @Context
	 UriInfo uriInfo;
	 @Context
	 Request request;
	 

	 	@Path("/narudzbenica/{id}")
		@GET
		@Produces(MediaType.APPLICATION_XML)
		public Narudzbenica vratiNarudzbenicu(@PathParam("id")String id) {
			try {
				int idNarudzbenica = Integer.parseInt(id);
				DAOFactory.connect();
				Narudzbenica n = DAOFactory.getNarudzbenicaDAO().selectNarudzbenica(idNarudzbenica);
				DAOFactory.disconnect();
				return n;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	 	
	    @Path("/svi")
		@GET
		@Produces(MediaType.APPLICATION_XML)
		public GenericEntity<List<Narudzbenica>> vratiNarudzbenice() {
			try {
				DAOFactory.connect();
				List<Narudzbenica> narudzbenice = DAOFactory.getNarudzbenicaDAO().selectSveNarudzbenice();
				DAOFactory.disconnect();
				return new GenericEntity<List<Narudzbenica>>(narudzbenice){};
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	
	 @PUT
	  @Path("narudzbenica/nova")
	  @Consumes(MediaType.APPLICATION_XML)
	  @Produces(MediaType.APPLICATION_XML)
	  public String putNarudzbenica(@HeaderParam("username")String username, @HeaderParam("password")String password, Narudzbenica n) throws Exception {
		  try{
			  DAOFactory.connect();
			  DAOFactory.getNarudzbenicaDAO().insertNarudzenica(n);
			  DAOFactory.disconnect();
			  return Boolean.toString(true);
		  }
		  catch(Exception e){
			  e.printStackTrace();
			  return Boolean.toString(false);
		  }
	  }
	 
	  @POST
	  @Path("narudzbenica/obrisi")
	  @Consumes(MediaType.APPLICATION_XML)
	  @Produces(MediaType.APPLICATION_XML)
	  public String deleteNarudzbenica(@HeaderParam("username")String username, @HeaderParam("password")String password, String id){
		  try{
			  int idNarudzbenica = Integer.parseInt(id);
			  DAOFactory.connect();
			  int i = DAOFactory.getNarudzbenicaDAO().deleteNarudzbenica(idNarudzbenica);
			  if (i!=1){
				  DAOFactory.disconnect();
				  return Boolean.toString(false);
			  }
			  DAOFactory.disconnect();
			  return Boolean.toString(true);
		  }
		  catch(Exception e){
			  e.printStackTrace();
			  return Boolean.toString(false);
		  }
	  }
}
